package com.xiu.travel.socket;

import com.xiu.travel.util.api.CommonResult;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashSet;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author qianl
 * @date 2023/8/18 19:48
 * @since WebSocketServer
 */
@Component
@Slf4j
@Service
@ServerEndpoint("/portal/open/websocket/{id}/{client}")
@Tag(name = "WebSocket")
public class SocketServer {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static final AtomicInteger onlineCount = new AtomicInteger(0);
    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。
    private static final CopyOnWriteArraySet<SocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    //接收id
    String id = "";
    String client = "";
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    /**
     * 群发自定义消息
     */
    public static void sendMessage(String message, HashSet<WSBody> ids) throws IOException {
        log.info("推送消息到客户端 " + ids + "，推送内容:" + message);
        for (SocketServer item : webSocketSet) {
            //这里可以设定只推送给传入的id，为null则全部推送
            if (ids.size() == 0) {
                item.sendMessage(message);
            } else {
                for (WSBody o : ids) {
                    if (Objects.equals(o.id(), item.id) && Objects.equals(o.client(), item.client)) {
                        item.sendMessage(message);
                    }
                }
            }
        }
    }

    /**
     * 获取当前在线人数
     *
     * @return 在线人数
     */
    public static int getOnlineCount() {
        return onlineCount.get();
    }

    /**
     * 当前在线人数 +1
     */
    public static void addOnlineCount() {
        onlineCount.getAndIncrement();
    }

    /**
     * 当前在线人数 -1
     */
    public static void subOnlineCount() {
        onlineCount.getAndDecrement();
    }

    /**
     * 获取当前在线客户端对应的WebSocket对象
     *
     * @return webSocketSet
     */
    public static CopyOnWriteArraySet<SocketServer> getWebSocketSet() {
        return webSocketSet;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id, @PathParam("client") String client) {
        var hasIdAndClient = webSocketSet.stream().anyMatch(item -> Objects.equals(item.id, id) && Objects.equals(item.client, client));
        this.session = session;
        // 加入set中
        if (hasIdAndClient) {
            try {
                sendMessage(CommonResult.failed("has id and client").toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            webSocketSet.add(this);
            this.id = id;
            this.client = client;
            // 在线数加1
            addOnlineCount();
            try {
                sendMessage(CommonResult.success("连接成功").toString());
                log.info("有新" + "client:" + client + "开始监听,id=" + id + ",当前在线人数为:" + getOnlineCount());
            } catch (IOException e) {
                log.error("websocket IO Exception");
            }
        }

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  // 从set中删除
        subOnlineCount();              // 在线数减1
        // 断开连接情况下，更新主板占用情况为释放
        log.info("释放的id=" + id + "的client:" + client);
        releaseResource();
    }

    private void releaseResource() {
        // 这里写释放资源和要处理的业务
        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info(id + ":" + client + " :" + message);

        // 群发消息
        HashSet<WSBody> ids = new HashSet<>();
        for (SocketServer item : webSocketSet) {
            ids.add(new WSBody(item.id, item.client));
        }
        try {
            sendMessage(CommonResult.success(message).toString(), ids);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发生错误回调
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error(session.getBasicRemote() + "客户端发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送消息到 指定客户端
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

}
